package com.cheer.controller;

import cn.hutool.core.lang.UUID;
import com.cheer.common.Result;
import com.cheer.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/image")
@Slf4j
public class OaImageController {

    @Value("${image.dir}")
    private String imageDir;

    @PostMapping("/upload")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result upload(MultipartFile file) {
        String imageName = UUID.randomUUID().toString(true) + ".jpg";
        try {
            file.transferTo(new File(imageDir + imageName));
        } catch (IOException e) {
            log.error("图片上传异常", e);
            throw new ServiceException("图片上传异常");
        }
        return Result.success(imageName);
    }
}
